package mtyan;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class ProcessLogin
 */
public class ProcessLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProcessLogin() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		MySQLConnector connector = new MySQLConnector();
		String login = (String) request.getParameter("login");
		String password = (String) request.getParameter("password");
		List<List<String>> users = connector.executeQuery("*", 7, "user", "login='"+login+"' AND password='"+password+"'");
		String url = "/Login.jsp";
		if (users.size()>0){
			List<String> userList = users.get(0);
			User user = new User();
			user.setId(Integer.parseInt(userList.get(0)));
			user.setName(userList.get(1));
			user.setLastname(userList.get(2));
			user.setLogin(userList.get(3));
			user.setPassword(userList.get(4));
			user.setRole(userList.get(5));
			/*user.setBirthdate(birthdate);*/
			HttpSession session = request.getSession(true);
			session.setAttribute("user", user);
			url="/Events.jsp";
		}
		ServletContext context = getServletContext();
		RequestDispatcher requestDispatcher = context.getRequestDispatcher(url);
		requestDispatcher.forward(request, response);
	}
}
